namespace Ray.Web.Filters
{
    using System.Collections.Specialized;
    using Castle.MonoRail.Framework;
    using Ray.Web.Models;

    public class AuthenticationFilter: IFilter
    {
        public bool Perform(ExecuteEnum exec, IRailsEngineContext context, Controller controller)
        {
            // Read previous authenticated principal from session 
            // (could be from cookie although with more work)

            Ray_Master ray_Master = (Ray_Master)context.Session["Ray_Master"];

            // Sets the principal as the current user
            context.CurrentUser = ray_Master;

            // Checks if it is OK
            if (context.CurrentUser == null || !context.CurrentUser.Identity.IsAuthenticated)
            {
                // Not authenticated, redirect to login
                NameValueCollection parameters = new NameValueCollection();
                parameters.Add("ReturnUrl", context.Url);
                //controller.Redirect("admin","login", "index", parameters);
                controller.Redirect("Login","Index",parameters);
                // Prevent request from continue
                return false;
            }

            // Everything is ok
            return true;
        }
    }
}
